package controllers;

import helpers.DateHelper;
import helpers.PaginatorHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.ArticleModel;
import models.CategoryModel;
import models.UserModel;

import systems.Recently;
import entities.ApplicationConfig;
import entities.Article;
import entities.Category;
import entities.User;

public class ArchivesServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		ApplicationConfig appConfig = (ApplicationConfig) request.getAttribute("sysConfig");
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (name == null || name.isEmpty() || name.equalsIgnoreCase("/archives")) {
			Calendar cal = Calendar.getInstance();
			int month = cal.get(Calendar.MONTH) + 1;
			name = (month < 10 ? "0" + month : month) + "-" + cal.get(Calendar.YEAR);
		}
		String language = (String) request.getAttribute("language");
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		//Get article by category and paginator
		int page = 1;
		try {
			page = Integer.parseInt((String) request.getParameter("page"));
		} catch (Exception e) {}
		
		boolean nextPage = false;
		boolean prevPage = false;
		int limit = 100;
		
		ArticleModel articleModel = ArticleModel.getInstance();
		List<Article> articles = Recently.getArticles(appConfig.getApplicationId(), name, "archives");
		
		if (page > 1) {
			articles = articleModel.listByArchives(appConfig.getApplicationId(), name, page, limit, language);
		} else {
			List<Article> lsArticles = articleModel.listByArchives(appConfig.getApplicationId(), name, page, limit, language);
			if (articles.size() == 0 || articles.size() < lsArticles.size()) {
				for (int i = lsArticles.size() - 1; i >= 0; i--) {
					Recently.insertArticle(appConfig.getApplicationId(), name, "archives", lsArticles.get(i));
				}
				articles = Recently.getArticles(appConfig.getApplicationId(), name, "archives");
			}
		}
		
		if (articles.size() == limit) {
			nextPage = true;
		}
		
		if (page > 1) {
			prevPage = true;
		}
		
		//Get paginate
		String queryString = request.getQueryString();
		String requestURI = request.getRequestURI();
		PaginatorHelper paginator = new PaginatorHelper(queryString);
		paginator.setUrl(requestURI);
		
		//Get categories
		List<String> cIds = new ArrayList<String>();
		List<String> uIds = new ArrayList<String>();
		
		for (int i = 0; i < articles.size(); i++) {
			if (!articles.get(i).getCategory().isEmpty()) {
				cIds.add(articles.get(i).getCategory());
			}
			if (!articles.get(i).getCreator().isEmpty()) {
				uIds.add(articles.get(i).getCreator());
			}
		}
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		Map<String, Category> categories = categoryModel.getByListId(appConfig.getApplicationId(), cIds);
		
		UserModel userModel = UserModel.getInstance();
		Map<String, User> authors = userModel.getByListId(appConfig.getApplicationId(), uIds);
		
		String articleTitle = getMonthYear("01-" + name, "dd-MM-yyyy");
		
		request.setAttribute("name", name);
		request.setAttribute("articleTitle", articleTitle);
		request.setAttribute("articles", articles);
		request.setAttribute("categories", categories);
		request.setAttribute("authors", authors);
		request.setAttribute("paginator", paginator);
		request.setAttribute("prevPage", prevPage);
		request.setAttribute("nextPage", nextPage);
		request.setAttribute("page", page);
		try {
			request.getRequestDispatcher("/templates/" + appConfig.getTemplateId() + "/pages/archives.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
    	
	}
	
	private String getMonthYear(String inDate, String formatInput) {
		String name = "";
		
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(formatInput);
			

		dateFormat.setLenient(false);

		try {
			// parse the inDate parameter
			date = dateFormat.parse(inDate.trim());
		} catch (ParseException pe) {
		}
		
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		
		String month = DateHelper.getMonthName(cal.get(Calendar.MONTH));
		int year = cal.get(Calendar.YEAR);
		
		name = month + " " + year;
		
		return name;
	}
}
